<!--
 * @Descripttion: 目录管理
 * @version: 
 * @Author: 穆宏宇
 * @Date: 2020-11-23 13:56:38
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-11-24 14:25:25
-->
<template>
  <div class="catalogue-manager">
	<el-form  ref="queryForm" :inline="true" label-width="88px">
		<el-form-item label="供应商">
			<el-select v-model="gys" placeholder="请选择供应商" filterable clearable @change="changeSupplier()">
			  <el-option
			    v-for="item in supplierList"
			    :key="item.id"
			    :label="item.name"
			    :value="item.code">
			  </el-option>
			</el-select>
		</el-form-item>
		<el-form-item>
			<el-button size="mini" @click="changeSupplier()">搜索</el-button>
			<el-button size="mini" @click="reset">重置</el-button>
			<!-- <el-button size="mini" @click="setPrice">设置折扣率</el-button> -->
		</el-form-item>
        <!-- <el-button type="success" size="small" @click="openDialogEdit('root',{})" style="float: right;">
            新建根节点
		</el-button> -->
	</el-form>
	
    <el-table
      :data="tableData"
      ref="table"
      style="width: 100%"
      row-key="itemCategoryId"
      border
      lazy
      :load="load"
      :height="maxHeightNow"
	  :row-class-name="tableRowClassName"
      :tree-props="{children: 'children', hasChildren: 'haveChildren'}">
      <el-table-column
        prop="categoryName"
        label="商品目录">
      </el-table-column>
      <!-- <el-table-column
        label="平均折扣率">
        <template slot-scope="scope">
		  {{scope.row.discountRate.toFixed(2)}}
        </template>
      </el-table-column> -->
      <el-table-column
        label="预警">
        <template slot-scope="scope">
		 <p style="height: 40px;line-height: 40px;">{{scope.row.sku && scope.row.sku.length>0?scope.row.sku[0]:''}}
		 <el-button type="text" @click="goMore(scope.row)" style="float: right;" v-if="scope.row.sku && scope.row.sku.length>0">更多</el-button></p>
        </template>
      </el-table-column>
      <el-table-column
        label="当前折扣率">
        <template slot-scope="scope">
		  {{scope.row.itemRate}}
        </template>
      </el-table-column>
	  <el-table-column label="操作" v-if="currentType == 1">
		  <template slot-scope="scope">
			<el-button type="text" @click="setPrice(scope.row)" v-if="scope.row.categoryLevel == 1">设置折扣率</el-button>
		  </template>
	  </el-table-column>
    </el-table>
  
	<el-dialog title="更多预警信息" :visible.sync="dialogVisibleMore" width="80%" >
		<el-table
		  :data="skuArr"
		  ref="table"
		  style="width: 100%"
		  border>
		  <el-table-column
		    prop="categoryName"
		    label="sku">
			<template slot-scope="scope">
			{{scope.row.sku}}
			</template>
		  </el-table-column>
		  <el-table-column label="实际折扣率">
			<template slot-scope="scope">
			{{1-scope.row.discountRate}}
			</template>
		  </el-table-column>
		  <el-table-column label="预设折扣率">
			<template slot-scope="scope">
			{{1-scope.row.itemDiscountRate}}
			</template>
		  </el-table-column>
		  <el-table-column label="供应商">
			<template slot-scope="scope">
			{{scope.row.supplierName}}
			</template>
		  </el-table-column>
		  <el-table-column label="协议价格">
			<template slot-scope="scope">
			{{scope.row.agreementPrice.toFixed(2)}}
			</template>
		  </el-table-column>
		  <el-table-column label="官网价格">
			<template slot-scope="scope">
			{{scope.row.officialPrice.toFixed(2)}}
			</template>
		  </el-table-column>
	  </el-table>
	  
	  <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
	  	@pagination="goMore" />
	</el-dialog>
	
	<el-dialog title="设置折扣率" :visible.sync="dialogVisiblePrice" width="400px" >
		<el-form  ref="queryForm" :inline="true" label-width="88px">
			<el-form-item label="折扣率" prop="itemRate">
				<el-input type="number" v-model="itemRate" step="0.01"  placeholder="请输入折扣率" clearable size="small" />
			</el-form-item>
		</el-form>
		<div slot="footer" class="dialog-footer">
		  <el-button type="primary" @click="submitForm">确 定</el-button>
		  <!-- <el-button @click="cancel">取 消</el-button> -->
		</div>
	</el-dialog>
  </div>
</template>

<script>
import { queryGodCategoryZtreeAsyn,getGoodsItemInfomationbyfirst,getGoodsItemInfomationbytwo,getGoodsItemInfomationbythree, getQuerySupplier,systemRate,rateList,putSystemRate,getGoodsItemInfomationbyCategoryIdAndsupplierId,getQuerySupplierLocal } from '@/api/admin.api'
export default {
    name: 'catalogue-manager',
   data () {
     return {
        pageType: '',
        titleObj: {
          root: '新增根节点',
          new: '新增子节点',
          edit: '修改目录',
          root: '新增根节点',
        },
        tableData: [],
        dialogVisible: false,
        dialogVisibleSort: false,
		dialogVisibleMore:false,
		dialogVisiblePrice:false,
        form: {
          categoryName: '',
          sorts: '',
		  itemType:'自营'
        },
        parentName: '',
        sortForm: {
          itemOrder: '',
          itemType: ''
        },
        rules: {
          categoryName: [
            { required: true, trigger: 'blur',message: '请输入商品目录名称'}
          ],
          itemType: [
            { required: true, trigger: 'change',message: '请选择类型'}
          ]
        },
		gys:'',
		supplierList:[],
		supplierId:'',
		supplierName:'',
		supplierCode:'',
		itemCategoryId:'',
		itemCategoryName:'',
		itemRate:'',
		type:'add',
		currentType:'',
		skuArr:[],
		queryParams: {
			pageNum: 1,
			pageSize: 10,
		},
		total:0,
		lastItem:''
	 }
   },
    computed: {
    // 表格高度
    maxHeightNow () {
      const height = window.innerHeight
      return height - 162
    }
  },
   mounted(){
     this.getTree()
	 this.getQuerySupplierList()
	 var type = localStorage.getItem("authorities").indexOf("ROLE_Center_Admin");
	 if(type>-1){
		 this.currentType = 1;
	 }else{
		 this.currentType = 0;
	 }
   },
   methods: {
		tableRowClassName({row, rowIndex}) {
			if (row.discountRate<row.itemRate) {
			   return 'success-warn';
			}
			return '';
		},
	   changeSupplier(){
		   var that = this;
			that.supplierList.find(function(item) {
				if(item.code === that.gys){
					console.log(item.code + '----' + that.gys);
					that.supplierId = item.id;
					that.supplierName = item.name;
					that.supplierCode = item.code;
					//刷新列表
					that.getTree();
					return;
				}
			});
	   },
	   submitForm(){
		   var that = this;
		   var data = {
			   tenantId:'',
			   supplierId:that.supplierId,
			   supplierName:that.supplierName,
			   supplierCode:that.supplierCode,
			   itemCategoryId:that.itemCategoryId,
			   itemCategoryName:that.itemCategoryName,
			   itemRate:that.itemRate
		   }
		   if(that.type == 'add'){
			   systemRate(data).then(res=>{
				   console.log(res);
				   this.$message.success(res.msg);
				   this.dialogVisiblePrice = false;
				   this.getTree();
			   })
		   }else{
			   putSystemRate(data).then(res=>{
				   console.log(res);
				   this.$message.success(res.msg);
				   this.dialogVisiblePrice = false;
				   this.getTree();
			   })
		   }
	   },
	   getQuerySupplierList(){
		   getQuerySupplierLocal({
			   current: 1,
			   size: 999999999
		   }).then(res=>{
			   console.log(res);
			   this.supplierList = res.rows;
		   })
	   },
	   handleQuery(){
		   
	   },
	   reset(){
		   this.gys = '';
		   this.supplierId = '';
		   this.firstLevelDirectoryId = '';
		   this.getTree();
	   },
	   setPrice(row){
		   var that = this;
		   if(this.gys == ''){
			   return this.$message.error('请输入要设置的供应商');
		   }
		   this.itemRate = '';
		   this.itemCategoryId = row.itemCategoryId;
		   this.itemCategoryName = row.categoryName;
		   rateList({
			    itemCategoryId:that.itemCategoryId,
				supplierId:that.supplierId
		   }).then(res=>{
			   console.log(res);
			   if(res.rows.length>0){
				   that.itemRate = res.rows[0].itemRate;
				   that.type = 'edit';
			   }else{
				   that.type = 'add';
			   }
		   })
		   this.dialogVisiblePrice = true;
	   },
	   goMore(item){
		   var that = this;
		   console.log(item);
		   if(item){
			   that.lastItem = item;
		   }else{
			   item = that.lastItem;
		   }
		   this.queryParams.supplierId = that.supplierId;
		   if(item.categoryLevel == 1){
			   this.queryParams.firstLevelDirectoryId = item.itemCategoryId
		   }else if(item.categoryLevel == 2){
			   this.queryParams.secondaryDirectoryId = item.itemCategoryId
		   }else if(item.categoryLevel == 3){
			   this.queryParams.threeDirectoryId = item.itemCategoryId
		   }
		   getGoodsItemInfomationbyCategoryIdAndsupplierId(this.queryParams).then(res=>{
			   if(res.rows.length > 0){
				   this.dialogVisibleMore = true;
				   this.skuArr = res.rows;
				   this.total = res.total;
			   }else{
				   this.$message.error('暂无数据');
			   }
		   })
	   },
	   
	   // getTree(){
	   //   queryGodCategoryZtreeAsyn('','').then(res=>{
	   //      this.tableData = res
	   //   })
	   // },
	   //  load(tree, treeNode, resolve) {
	   //    const parentId =  tree.id
	   //    queryGodCategoryZtreeAsyn(parentId,'').then(res=>{
	   //      resolve(res)
	   //    }).catch(err=>{
	   //      console.log(err);
	   //      resolve([])
	   //    })
	   //  },
     getTree(){
		 var data = {
			 supplierId:this.supplierId,
			 firstLevelDirectoryId:this.itemCategoryId
		 }
		getGoodsItemInfomationbyfirst(data).then(res=>{
		   console.log(res);
		  this.tableData = res
		})
     },
      load(tree, treeNode, resolve) {
		  if(tree.categoryLevel == 1){
			 var data = {
				 supplierId:this.supplierId,
				 firstLevelDirectoryId:tree.itemCategoryId
			 }
			  getGoodsItemInfomationbytwo(data).then(res=>{
			  			resolve(res)
			  }).catch(err=>{
			  			console.log(err);
			  			resolve([])
			  })
		  }else{
			  var data = {
				 supplierId:this.supplierId,
				 secondaryDirectoryId:tree.itemCategoryId
			  }
			  getGoodsItemInfomationbythree(data).then(res=>{
				  debugger
			  			resolve(res)
			  }).catch(err=>{
			  			console.log(err);
			  			resolve([])
			  })
		  }
      },
      refreshRow(id){
        queryGodCategoryZtreeAsyn(id,'').then(res => {
          if (res&&res.length) {
            this.$set(this.$refs.table.store.states.lazyTreeNodeMap, id, res)
          }
        })
      },
      openDialogEdit(type,row){
        this.pageType = type
        const {categoryName, sorts, id, parentCategoryId, categoryLevel} = row
        switch (type) {
          case 'root':
            this.form = {v: '1',categoryLevel: '1',itemType:row.categoryItemType}
            this.dialogVisible = true
            break;
          case 'new':
            this.parentName = categoryName
            this.form = {parentCategoryId: id, v: '1',categoryLevel: categoryLevel?categoryLevel+1:1,itemType:row.categoryItemType}
            this.dialogVisible = true
            break;
          case 'edit':
            this.form = {categoryName, sorts, id, parentCategoryId, categoryLevel,itemType:row.categoryItemType}
            this.dialogVisible = true
            break;
          default:
            break;
        }
      },
      save(row){
        let pid = this.form.parentCategoryId||''
        this.$refs.form.validate((valid) => {
          if (valid) {
            switch (this.pageType) {
              case 'root':
              case 'new':
                addItemCategory(this.form).then(res=>{
                  this.$alert('保存成功', '提示', {
                    confirmButtonText: '确定',
                    type: 'success',
                    callback: action => {
                      this.parentName = ''
                      this.refreshRow(pid)
                      this.dialogVisible = false;
                    }
                  })
                })
                break;
              case 'edit':
                editItemCategory(this.form).then(res=>{
                  this.$alert('保存成功', '提示', {
                    confirmButtonText: '确定',
                    type: 'success',
                    callback: action => {
                      if (pid) {
                        this.refreshRow(pid)
                      }else{
                        this.getTree()
                      }
                      this.dialogVisible = false;
                    }
                  })
                })
                break;
            
              default:
                break;
            }
          }
        })
      },
      // 设置有效性
      invalidItemCategoryFn(row){
        const data = {
          id: row.id,
          v: row.v==='1'?'0':'1'
        }
        const pid = this.form.parentCategoryId||''
        this.$alert(`确定置为${row.v==='1'?'无效':'有效'}吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success',
          callback: action => {
            if (action === 'confirm') {
              invalidItemCategory(data).then(res=>{
                this.$alert('保存成功', '提示', {
                  confirmButtonText: '确定',
                  type: 'success',
                  callback: action => {
                    if (pid) {
                      this.refreshRow(pid)
                    }else{
                      this.getTree()
                    }
                  }
                })
              })
            }
          }
        })
      },
      // 以下fn 第二个弹窗相关
      openDialogSort(row){
        this.sortForm.categoryId = row.id
        this.sortForm.itemType = row.itemType
        this.sortForm.itemOrder = row.itemOrder
        this.dialogVisibleSort = true
      },
      saveSort(){
        this.$refs.sortForm.validate((valid) => {
          if (valid) {
            let data = {
              // NavUpdateDtoNavUpdateDto: {
                categoryId: this.sortForm.categoryId,
                itemOrder: this.sortForm.itemOrder,
                itemType: this.sortForm.itemType,
              // }
            }
            updateOfficeSupplies(data).then(res=>{
                this.$alert('保存成功', '提示', {
                  confirmButtonText: '确定',
                  type: 'success',
                  callback: action => {
                    this.getTree()
                    this.dialogVisibleSort = false
                  }
                })
            })
          }
        })
      }
   }
}
</script>

<style lang='scss'>

  .catalogue-manager {
    th,
    td,
    tr {
      text-align: left !important;
      padding-left: 40px;
      padding-right: 40px;
    }
    .mb10{
      margin-bottom: 10px;
    }
  }
  .success-warn{
	  background: #dcffce !important;
  }
</style>
